import { ReactElement, useRef, useEffect } from 'react'
import { Modal, Form, FormInstance, Input, Radio, message } from 'antd'
import { SystemQuestionSchema } from '@src/components/schema/systemQuestion'
import Upload, { uploadFile } from '@components/upload'
import { FileSchema } from '@src/components/schema/fileSchema'
import { awaitWrap } from '@src/assets/js/tool'
import { createRequest, updateRequest } from './ajax'

const { Item } = Form
const { TextArea } = Input

interface FormData {
  file: FileSchema[]
}

async function submitHandle (d: FormData, refreshFn: () => void): Promise<void> {
  const data: { [k: string]: any } = { ...d }
  if (d.file instanceof Array) {
    const [e, r] = await awaitWrap(uploadFile(d.file))
    if (e === null && r instanceof Array) {
      data.fileid = r.map(li => li.id).join()
    }
  }
  data.status = '提交'
  delete data.file
  if (data.id !== undefined) {
    await updateHandle(data, refreshFn)
  } else {
    await addHandle(data, refreshFn)
  }
}

async function updateHandle (data: { [k: string]: any }, refreshFn: () => void): Promise<void> {
  const hide = message.loading('提交中', 120)
  const [e] = await awaitWrap(updateRequest(data))
  hide()
  if (e === null) {
    message.success('更新成功').then(null, null)
    refreshFn()
  }
}

async function addHandle (data: { [k: string]: any }, refreshFn: () => void): Promise<void> {
  const hide = message.loading('提交中', 120)
  const [e] = await awaitWrap(createRequest(data))
  hide()
  if (e === null) {
    message.success('新增成功').then(null, null)
    refreshFn()
  }
}

interface Props {
  data: SystemQuestionSchema | null
  visible: boolean
  hide: () => void
  refreshFn: () => void
}

function Main ({ data, visible, hide, refreshFn }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  const title = data === null ? '新增问题' : '编辑问题'
  useEffect(() => {
    const c = formRef.current
    if (c !== null) {
      if (data !== null) {
        const d: { [k: string]: any } = { ...data }
        if (d.file instanceof Array) {
          d.file.forEach((li: FileSchema) => {
            li.name = li.original_filename
          })
        }
        c.setFieldsValue(d)
      } else {
        c.resetFields()
      }
    }
  }, [data])
  useEffect(() => {
    const c = formRef.current
    if (c !== null && !visible) {
      c.resetFields()
    }
  }, [visible])
  return (
    <Modal title={title} visible={visible} onCancel={hide} onOk={() => formRef.current?.submit()}>
      <Form ref={formRef} labelCol={{ flex: '88px' }} initialValues={{ isqa: 0 }} onFinish={async d => await submitHandle(d, refreshFn)}>
        <Item name='id' noStyle><span /></Item>
        <Item label='标题' name='title'>
          <Input placeholder='请输入' />
        </Item>
        <Item label='问题描述' name='content'>
          <TextArea placeholder='请输入' rows={3} />
        </Item>
        <Item label='常见问题' name='isqa'>
          <Radio.Group>
            <Radio value={1}>是</Radio>
            <Radio value={0}>否</Radio>
          </Radio.Group>
        </Item>
        <Item name='file' label='截图上传'>
          <Upload accept='.jpg,.jpeg,.png,.pdf,.doc,.docx,.xlsx,.xls,.rar,.zip' />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
